﻿/**
* showLoaderWhen replaces the content of a container with a loading spinner
* when the bound value is truthy.
* Styling requires the .loader class to be defined for the page as well as the loaderClass property 
* (or a default of .loader-dark)
*/
ko.bindingHandlers.showLoaderWhen = {
	init: function (element, valueAccessor, allBindingsAccessor) {
		var loaderClass = ko.utils.unwrapObservable(allBindingsAccessor()).loaderClass || "loader-white",
			hideChildren = ko.utils.unwrapObservable(allBindingsAccessor()).hideChildren || false,
			$element = $(element),
			currentPosition = $element.css("position"),
			$loader = $("<div>", { "class": loaderClass }).addClass("loader").hide();

		//add the loader
		$element.append($loader);
		$element.data('hide-children-on-loading', hideChildren);
		//make sure that we can absolutely position the loader against the original element
		if (currentPosition === "auto" || currentPosition === "static") {
			$element.css("position", "relative");
		}

		var paddingTop = parseInt($element.css('padding-top')),
		    paddingRight = parseInt($element.css('padding-right')),
		    paddingBottom = parseInt($element.css('padding-bottom')),
		    paddingLeft = parseInt($element.css('padding-left'));

		$loader.css({
			'margin': paddingTop + 'px ' + paddingRight + 'px ' + paddingBottom + 'px ' + paddingLeft + 'px',
			'width': $element.width(),
			'height': $element.height()
		});

		$element.css('min-height', '100px');
	},
	update: function (element, valueAccessor, allBindingsAccessor) {
		var loaderClass = ko.utils.unwrapObservable(allBindingsAccessor()).loaderClass || "loader-white",
			isLoading = ko.utils.unwrapObservable(valueAccessor()),
			$element = $(element),
			hideChildren = $element.data('hide-children-on-loading'),
			$childrenToHide = $element.children(":not(div.loader)"),
			$loader = $element.find("div.loader");

		if ($loader.length === 0) {
			$loader = $("<div>", { "class": loaderClass }).addClass("loader").hide();
			$element.append($loader);
			$loader.css('margin', $element.css('padding'));
		}

		if (isLoading) {
			$loader.css({
				'width': $element.width(),
				'height': $element.height()
			});

			if (hideChildren) {
				$childrenToHide.css("visibility", "hidden").attr("disabled", "disabled");
			}
			$loader.show();
		}
		else {
			$loader.fadeOut("fast");
			if (hideChildren) {
				$childrenToHide.css("visibility", "visible").removeAttr("disabled");
			}
		}
	}
};